# coding:utf-8

import pymysql

db = pymysql.connect(host='localhost', port=3306, db='cloud_music', user='root', password='root')

sql_save = r'''
    insert into songlist_songlist(name, creator, url, view_counts) values("%s", "%s", "%s", "%s")')
'''


def save_song_to_db(song_list):
    try:
        cursor = db.cursor()
        for song_dict in song_list:
            sql = sql_save % (song_dict['name'], song_dict['creator'], song_dict['url'], song_dict['view_counts'])
            # print(sql)
            cursor.execute(sql)
            db.commit()
    except Exception as e:
        print(e)
        db.rollback()


def db_close():
    db.close()
